package com.cet.lxf.collection.test11;

import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @program: algorithm
 * @description: 中缀表达式转换为后缀表达式
 * @author: 陈恩涛
 * @create: 2021-08-16 22:37
 **/
public class Main01 {
    public static void main(String[] args) {
        String exp = "1 + 2 * (9 - 5)";
        SuffixExpression se = compile(exp);
        int result = se.execute();
        System.out.println(exp + " = " + result + " " + (result == 1 + 2 * (9 - 5) ? "✓" : "✗"));
    }

    /*
     * 中缀表达式转后缀表达式思路如下：
     * 1、从左到右扫描，遇到操作数直接输出
     * 2、当遇到操作符时
     *       1）当栈为空时，操作符入栈
     *       2）如果该操作符优先级大于等于栈顶操作符的优先级，则该操作符入栈
     *       3）如果该操作符优先级小于栈顶操作符的优先级，则栈顶操作符连续出栈并输出，直到栈顶操作符优先级小于该操作符，该操作符入栈
     *       4）遇到(则入栈，(只有遇到)才出栈
     *       5）遇到），栈顶操作符连续出栈并输出，直到遇到(
     * 3、当表达式扫描完后，栈中依然有操作符，则直接将栈中的操作符出栈并输出
     *
     * */

    private static SuffixExpression compile(String exp) {
        // TODO:
        StringBuilder sufExp = new StringBuilder();
        Deque<String> stack = new LinkedList<>();
        for (int i = 0; i < exp.length(); i++) {
            String s = exp.substring(i, i + 1);
            if (s.matches("\\s")) {
                continue;
            }
            if ("+".equals(s) || "-".equals(s) || "*".equals(s) || "/".equals(s)) {
                if (stack.isEmpty()) {
                    stack.push(s);
                } else if (compareOpt(s, stack.peek()) >= 0) {
                    stack.push(s);
                } else {
                    while (!stack.isEmpty() && compareOpt(s, stack.peek()) <= 0 && !"(".equals(s)) {
                        sufExp.append(stack.pop());
                    }
                    stack.push(s);
                }
            } else if ("(".equals(s)) {
                stack.push(s);
            } else if (")".equals(s)) {
                while (!"(".equals(stack.peek())) {
                    sufExp.append(stack.pop());
                }
                stack.pop();
            } else {
                sufExp.append(s);
            }
        }
        while (!stack.isEmpty()) {
            sufExp.append(stack.pop());
        }
        return new SuffixExpression(sufExp.toString());
    }

    private static int compareOpt(String op1, String op2) {
        List<String> optList = Arrays.asList("+", "-", " ", "*", "/");
        if (optList.indexOf(op1) - optList.indexOf(op2) >= 2) {
            return 1;
        } else if (optList.indexOf(op1) - optList.indexOf(op2) <= -2) {
            return -1;
        } else {
            return 0;
        }
    }
}

class SuffixExpression {

    private String exp;

    private static final Pattern ONE_NUM_PATTERN = Pattern.compile("\\d");
    private static final Pattern ONE_OPT_PATTERN = Pattern.compile("[\\+\\-\\*\\/]");

    public SuffixExpression(String exp) {
        this.exp = exp;
    }

    private int calculate(String leftOptValue, String operator, String rightOptValue) {
        int left = Integer.parseInt(leftOptValue);
        int right = Integer.parseInt(rightOptValue);
        int result = 0;
        switch (operator) {
            case "+":
                result = left + right;
                break;
            case "-":
                result = left - right;
                break;
            case "*":
                result = left * right;
                break;
            case "/":
                result = left / right;
                break;
            default: break;
        }
        return result;
    }

    int execute() {
        // TODO:
        Deque<String> stack = new LinkedList<>();
        for (int i = 0; i < this.exp.length(); i++) {
            String s = this.exp.substring(i, i + 1);
            if (ONE_NUM_PATTERN.matcher(s).matches()) {
                stack.push(s);
            } else if (ONE_OPT_PATTERN.matcher(s).matches()) {
                String rightOptValue = stack.pop();
                stack.push(String.valueOf(calculate(stack.pop(), s, rightOptValue)));
            } else {
                throw new RuntimeException("表达式不合法！");
            }
        }
        if  (stack.size() != 1) {
            throw new RuntimeException("表达式不合法！");
        }
        return Integer.parseInt(stack.pop());
    }
}
